package com.wjk.kylin.modules.system.dict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjk.kylin.core.common.redis.RedisRepository;
import com.wjk.kylin.core.constant.Constants;
import com.wjk.kylin.core.exception.BusinessException;
import com.wjk.kylin.modules.system.dict.entity.DictType;
import com.wjk.kylin.modules.system.dict.mapper.DictTypeMapper;
import com.wjk.kylin.modules.system.dict.service.IDictTypeService;
import com.wjk.kylin.modules.system.dict.service.IDictValueService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * <p>
 *  字典类型表 服务实现类
 * </p>
 *
 * @author wangjkui
 * @since 2020-06-07
 */
@Service
@Transactional(readOnly=true)
public class DictTypeServiceImpl extends ServiceImpl<DictTypeMapper, DictType> implements IDictTypeService {

    @Autowired
    private IDictValueService dictValueService;
    @Autowired
    private RedisRepository redisRepository;

    @Override
    public IPage<DictType> findPage(Page<DictType> page, DictType dictType) {
        return baseMapper.findPage(page,dictType);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean save(DictType dictType) {
        //1.判断type是否已经存在
        QueryWrapper<DictType> wrapper = new QueryWrapper<>();
        wrapper.eq("type", dictType.getType());
        int count = this.count(wrapper);
        if(count > 0){
            throw new BusinessException("字典类型已存在，请重新添加");
        }

        dictType.preInsert();
        return super.save(dictType);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean update(DictType dictType) {
        //1.判断type是否已经存在
        QueryWrapper<DictType> wrapper = new QueryWrapper<>();
        wrapper.eq("type", dictType.getType());
        wrapper.ne("id", dictType.getId());
        int count = this.count(wrapper);
        if(count > 0){
            throw new BusinessException("字典类型已存在，请重新修改");
        }

        //如果修改type，就只能充数据库查询之前的type，还要修改dictValue数据
        DictType oldDictType = super.getById(dictType.getId());

        //2.修改时间等
        dictType.preUpdate();

        //3.type也修改了，子表数据type，并且删除缓存
        if(!StringUtils.equals(oldDictType.getType(),dictType.getType())){
            dictValueService.updateTypeByType(dictType.getType(),oldDictType.getType());
            //1.删除缓存
            redisRepository.del(Constants.CACHE_DICT_REDIS_KEY  + oldDictType.getType());
        }
        //4.修改数据库

        return super.updateById(dictType);
    }

    @Override
    @Transactional(readOnly=false)
    public boolean deleteByIds(String[] dictTypeIds) {
        List<String> ids = Arrays.asList(dictTypeIds);

        List<DictType> list = super.listByIds(ids);

        List<String> types = list.stream().map(DictType::getType).collect(Collectors.toList());

        //2.刪除子类数据,并且删除缓存
        dictValueService.deleteByType(types);

        //3.删除数据库
        return super.removeByIds(ids);
    }

    @Override
    public void clearCache() {
        //清除字典配置的缓存
        Set<String> keys = redisRepository.keys(Constants.CACHE_DICT_REDIS_KEY);

        if(CollectionUtils.isNotEmpty(keys)){

            redisRepository.del(keys.toArray(new String[] {}));
        }

    }
}
